import axios from "axios";
import {getRefresh} from '../api/index.js'

// 创建axios实例的方法
export function createAxios(options = {}) {
  return axios.create({ ...options });
}

export const AxiosServer = createAxios({
  baseURL: "http://localhost:3088",
  headers: {
    Authorization: "AUTH_TOKEN_INSTANCE",
  },
  timeout: 5000,
});

// 是否要刷新
var isRefreshing = false
var requests = []
// 对实例进行拦截
// 请求拦截器
AxiosServer.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem('access_token');
    if (token) {
      config.headers.Authorization='Bearer ' + token || ''
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
AxiosServer.interceptors.response.use(
  async (response) => {
    // console.log("response", response.data);
    if (response.data.msg == '刷新令牌已过期' || response.data.msg == '无效的刷新令牌') {
      //这里是长token失效走的接口
      //在这里可以进行登录页跳转等操作
      // alert('登录凭证过期,请重新登录')
      localStorage.clear()   //删除缓存
      // localStorage.removeItem('refresh_token')
      isRefreshing = false  //请求成功开始刷新表示
      requests = []       //置空
      window.location.replace('/l/login')
      return false
    }

    if (response.data.code === 401) {
        console.log('检查到短token失效,进入这里');
        if (!isRefreshing) {
            console.log('短token失效,准备刷新');
            isRefreshing = true
            const RefreshToken = localStorage.getItem('refresh_token')
            const res = await getRefresh({ RefreshToken: RefreshToken })
            console.log('res的信息', res.msg);
            isRefreshing = false
            if(res){
              //重新设置长token与短token
              localStorage.setItem('access_token', res.accessToken)
              localStorage.setItem('refresh_token', res.refreshToken)
            }
            //重新将队列中事件执行
            requests.forEach((item) => item(res?.accessToken))
            requests = []
        }
        return new Promise((resolve) => {
            requests.push((token) => {
                response.config.headers.Authorization = `Bearer ${token}`
                resolve(AxiosServer(response.config))
            })
        })
    }

    if (!response.data && response.data.code != 0) {
        alert(response.data.message)
    }
    return response.data;
  },
  (error) => {
    console.log(error);
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          error.message = "未授权，请登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`;
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器内部错误";
          break;
        case 501:
          error.message = "服务未实现";
          break;
        case 502:
          error.message = "网关错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网关超时";
          break;
        case 505:
          error.message = "HTTP版本不受支持";
          break;
        default:
          error.message = "未知错误";
      }

      let errorData = {
        code: error.response.status,
        message: error.message,
      };

      console.log(errorData);
    }
    return Promise.reject(error);
  }
);
